﻿using CleanArchitecture.Infrastructure.Entities.Settings;
using FluentValidation.Validators;
using System.Text.RegularExpressions;

namespace CleanArchitecture.Web.Validators
{
    /// <summary>
    /// Username validator
    /// </summary>
    public class AdminUserLoginNamePropertyValidator : PropertyValidator
    {
        private readonly AdminUserSettings _adminuserSettings;

        /// <summary>
        /// Ctor
        /// </summary>
        public AdminUserLoginNamePropertyValidator(AdminUserSettings adminuserSettings)
            : base(ValidatorRuleString.LoginNameNotValid)
        {
            this._adminuserSettings = adminuserSettings;
        }

        /// <summary>
        /// Is valid?
        /// </summary>
        /// <param name="context">Validation context</param>
        /// <returns>Result</returns>
        protected override bool IsValid(PropertyValidatorContext context)
        {
            return IsValid(context.PropertyValue as string, _adminuserSettings);
        }

        /// <summary>
        /// Is valid?
        /// </summary>
        /// <param name="username">Username</param>
        /// <param name="customerSettings">Customer settings</param>
        /// <returns>Result</returns>
        public static bool IsValid(string loginusername, AdminUserSettings adminuserSettings)
        {
            return adminuserSettings.UserLoginnameValidationUseRegex && !string.IsNullOrEmpty(adminuserSettings.UserLoginnameValidationRule)
                    ? Regex.IsMatch(loginusername, adminuserSettings.UserLoginnameValidationRule, RegexOptions.CultureInvariant | RegexOptions.IgnoreCase)
                    : !string.IsNullOrEmpty(loginusername);
        }
    }
}
